package com.tg.service.flow.ui.superFlow;

import com.google.common.collect.Lists;
import com.tg.service.flow.EngineTest;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

public class SpFlowService {

    public boolean save(SpFlow flow) {
        List<SpFlowNode> nodes = flow.getNodes();
        List<SpFlowLink> links = flow.getLinks();

        Map<String, List<String>> map = new HashMap<>();
        for (SpFlowLink link : links) {
            if (map.containsKey(link.getStartId())) {
                map.get(link.getStartId()).add(link.getEndId());
            } else {
                map.put(link.getStartId(), Lists.newArrayList(link.getEndId()));
            }
        }

        //校验全部id非重复、key非空

        //设置metaId
        for (SpFlowNode node : nodes) {
            SpFlowNodeMeta meta = node.getMeta();
            //设置meta id
            if (Objects.isNull(meta.getId()) ||
                    !Objects.equals(node.getId(), meta.getId())) {
                meta.setId(node.getId());
            }

            //设置meta beStart
            if ("start".equals(meta.getProp())) {
                meta.setBeFirst(true);
            }

            //设置nextId
            if (map.containsKey(node.getId())) {
                List<String> nextIds = map.get(node.getId());
                meta.setNextIds(nextIds);
            }

            //设置condition
            links.stream()
                    .filter(li -> Objects.equals(node.getId(), li.getEndId()))
                    .findFirst()
                    .ifPresent(spFlowLink -> meta.setCondition(spFlowLink.getMeta().getDesc()));
        }

        EngineTest.OUT_DTO = flow;

        return true;
    }
}
